# -*- coding: utf-8 -*-
"""
数据模型基类

提供所有模型的基础字段和功能
"""

from datetime import datetime
from sqlalchemy import Column, Integer, DateTime, String, Boolean, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session

Base = declarative_base()


class BaseModel(Base):
    """
    基础模型类
    
    所有业务模型都应该继承此类，提供统一的基础字段和功能
    """
    __abstract__ = True

    # 主键
    id = Column(Integer, primary_key=True, index=True, comment="主键ID")
    
    # 审计字段
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment="更新时间")
    created_by = Column(String(50), comment="创建人")
    updated_by = Column(String(50), comment="更新人")
    
    # 软删除
    is_deleted = Column(Boolean, default=False, nullable=False, comment="是否已删除")
    deleted_at = Column(DateTime, comment="删除时间")
    deleted_by = Column(String(50), comment="删除人")
    
    # 备注字段
    remarks = Column(Text, comment="备注")

    def to_dict(self, exclude_fields=None):
        """转换为字典格式"""
        if exclude_fields is None:
            exclude_fields = []
        
        result = {}
        for column in self.__table__.columns:
            if column.name not in exclude_fields:
                value = getattr(self, column.name)
                if isinstance(value, datetime):
                    value = value.isoformat()
                result[column.name] = value
        return result

    def update_from_dict(self, data: dict, exclude_fields=None):
        """从字典更新模型"""
        if exclude_fields is None:
            exclude_fields = ['id', 'created_at', 'created_by']
        
        for key, value in data.items():
            if key not in exclude_fields and hasattr(self, key):
                setattr(self, key, value)

    def mark_deleted(self, operator: str = None):
        """标记为已删除（软删除）"""
        self.is_deleted = True
        self.deleted_at = datetime.utcnow()
        self.deleted_by = operator

    def restore(self, operator: str = None):
        """恢复已删除的记录"""
        self.is_deleted = False
        self.deleted_at = None
        self.deleted_by = None
        self.updated_by = operator
        self.updated_at = datetime.utcnow()

    @classmethod
    def get_active_query(cls, db: Session):
        """获取未删除记录的查询"""
        return db.query(cls).filter(cls.is_deleted == False)

    def __repr__(self):
        return f"<{self.__class__.__name__}(id={self.id})>"